package com.westcom.vulb.activity;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.westcom.vulb.application.GlobalContext;
import com.westcom.vulb.bean.Session;
import com.westcom.vulb.logic.account;
import com.westcom.vulb.logic.SessionManager;
import com.westcom.vulb.logic.card;
import com.westcom.vulb.logic.category;
import com.westcom.vulb.logic.resource;
import com.westcom.vulb.logic.sheet;
import com.westcom.vulb.protocal.http.Response;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class LoginActivity extends BasicActivity {
    private ProgressDialog mLoadingDialog;
    private LoginTask mLoginTask;
    private SessionManager sm;
    
    EditText m_et_accont = null;
    EditText m_et_pass = null;
    String m_account = "";
    String m_pass = "";
    TextView m_tv_remind = null;
    
    TextView mTvHeaderLeft = null;
    TextView mTvHeaderMid = null;
    boolean is_logining = false;
    
    private static final String TAG = "LoginActivity";
    private void autoLogin()
    {
    	SharedPreferences info = this.getSharedPreferences(SessionManager.logged_user_info,0);
    	m_account = info.getString(SessionManager.current_user_account,"");
    	m_pass = info.getString(SessionManager.current_user_password,"");
    	if(!m_account.equals("") && !m_pass.equals("") && !is_logining)
    	{
    		m_et_accont.setText(m_account);
            m_et_pass.setText(m_pass);
    		mLoadingDialog = ProgressDialog.show(LoginActivity.this, "Login", "Login...");
    		mLoginTask = new LoginTask();
            mLoginTask.execute("");
    	}
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        OnClickListener l = new OnClickListener()
        {
			@Override
			public void onClick(View v) 
			{
				switch(v.getId())
				{
					case R.id.btn_login:
					{
						if(is_logining)
		            	{
		            		return;
		            	}
		                m_account = m_et_accont.getText().toString();
		                m_pass = m_et_pass.getText().toString();
		                if(null == m_account||m_account.equals(""))
		                {
		                	launchToast(R.string.email_empty_error);
		                	return;
		                }
		                if(null == m_pass||m_pass.equals(""))
		                {
		                	launchToast(R.string.pwd_empty_error);
		                	return;
		                }
		                mLoadingDialog = ProgressDialog.show(LoginActivity.this, "Login", "Login...");
		                mLoginTask = new LoginTask();
		                mLoginTask.execute("");
					}break;
					case R.id.login_header_left:
					{
						finish();
					}break;
					default:{}break;
				}
			}
        };
        View loginBtn = findViewById(R.id.btn_login);
        mTvHeaderLeft = (TextView)this.findViewById(R.id.login_header_left);
        mTvHeaderMid = (TextView)this.findViewById(R.id.login_header_mid);
        loginBtn.setOnClickListener(l);
        mTvHeaderLeft.setOnClickListener(l);
        m_et_accont = (EditText)findViewById(R.id.et_login_accont);
        m_et_pass = (EditText)findViewById(R.id.et_login_pass);
        GlobalContext.getInstance().Init(this);
        sm = SessionManager.getInstance();
        m_tv_remind = (TextView)this.findViewById(R.id.tv_login_remind);
        //
        int remind = this.getIntent().getIntExtra("remind",-1);
        if(remind > 0)
        {
        	m_tv_remind.setVisibility(View.VISIBLE);
        	m_tv_remind.setText(remind);
        }else
        {
        	m_tv_remind.setVisibility(View.GONE);
        }
        //
        int header = this.getIntent().getIntExtra("header", -1);
        if(header > 0)
        {
        	mTvHeaderMid.setText(header);
        }else
        {
        	mTvHeaderMid.setText(R.string.login_title);
        }
        autoLogin();
    }
    private void getCard()
    {
    	Response sheet_res;
    	sheet_res = sheet.getInstanse().GetSheetList(sm.getCurrentSession().getSessionid());
    	try
    	{
    		if(sheet_res.errno == Response.SUCCESS)
        	{
        		JSONArray sheets = (JSONArray)sheet_res.data.get("sheets");
        		JSONObject sheet = null;
        		sheet = sheets.getJSONObject(0);
        		if(null != sheet)//find sheet
        		{
        			Response category_res;
        			category_res = category.getInstanse().GetCategoryList(sm.getCurrentSession().getSessionid(), sheet.optInt("sheetId"));
        			if(category_res.errno == Response.SUCCESS)
        			{
        				JSONObject category = null;
        				JSONArray categorys = (JSONArray)category_res.data.get("categorized0");//categorized1  uncategorized
        				category = categorys.getJSONObject(0);
        				if(null != category)//find category
        				{
        					int categoryId = category.optInt("categoryId");
        					JSONArray cates = new JSONArray();
        					JSONObject cate = new JSONObject();
        					cate.put("categoryId",categoryId);
        					cate.put("start",0);
        					cate.put("count",3);
        					cates.put(cate);
        					Response card_res = card.getInstanse().GetCardList(sm.getCurrentSession().getSessionid(),cates);
        					HashMap<String,Object> card_cate = (HashMap<String,Object>)card_res.data.get("categories");
        					JSONArray cards = (JSONArray)(card_cate.get(""+categoryId));
        					JSONObject card = cards.getJSONObject(0);//find card
        					
        					Response resource_response = resource.getInstance().ReferenceThumbnailImage(sm.getCurrentSession().getSessionid(),card.getInt("resourceId"));
        	            	Bitmap Thumbnail = account.Base64Str2Bitmap((String)resource_response.data.get("resourceData"));
        	            	//saveBitmap(Thumbnail,saveDir+"Thumbnail.jpg");
        	            	
        	            	resource_response = resource.getInstance().ReferenceResourceInCard(sm.getCurrentSession().getSessionid(),card.getInt("resourceId"));
        	            	Bitmap source = account.Base64Str2Bitmap((String)resource_response.data.get("resourceData"));
        	            	//saveBitmap(source,saveDir+"source.jpg");
        				}
        			}
        		}
        	}
    	}catch (Exception e) 
    	{
    		
    	}
    }
    private static final int MSG_GET_RESOURCE_DONE = 0x01;
    private Handler mhandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) 
        {
        	switch (msg.what)
        	{
	        	case MSG_GET_RESOURCE_DONE:
	        	{
	        		Session.getResourceResponse res = null;
	        		String erromsg = null;
	        		String filePath = null;
	        		int resId = 0;
	        		if(msg.arg1 == Response.SUCCESS)
	        		{
	        			res = (Session.getResourceResponse)msg.obj;//success
	        		}else
	        		{
	        			erromsg = res.httpRes.errmsg;//failed
	        		}
	        		filePath = res.filePath;
	        		resId = res.resId;
	        		Log.e(TAG,"filePath:"+filePath+", resId:"+resId+", erromsg:"+erromsg);
	        	}break;
	        	default:{}break;
        	}
        }
    };
    
    private class LoginTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
        	is_logining = true;
            account loginLogic = account.getInstanse();
            Response response = loginLogic.login(m_account, m_pass);
            Message.obtain(mHttpResponseHandler, HTTP_RESPONSE_STATUS, response.errno, 0).sendToTarget();  
            if (response.errno == Response.SUCCESS) 
            {
            	//getCard();
            	/*
            	response = resource.getInstance().GetDownloadKey(sm.getCurrentSession().getSessionid(),5961);
            	Integer confirmId = (Integer)response.data.get("confirmId");
            	String confirmKey = (String)response.data.get("confirmKey");
            	String bn_res = resource.getInstance().BinaryDownload(sm.getCurrentSession().getSessionid(), 5961,confirmId,confirmKey);
            	Charset cs = Charset.forName("UTF-8");
            	saveBinaryFile(bn_res,saveDir+"bin.jpg");
            	*/
            	//s.getResource(7441, 0, mhandler.obtainMessage(MSG_GET_RESOURCE_DONE));
            	//s.getResource(7441, 1, mhandler.obtainMessage(MSG_GET_RESOURCE_DONE));
            	/*Response res = account.getInstanse().GetProfileImage(66,"",sm.getCurrentSession().getSessionid());
    			String bitmap_str = (String) res.data.get("personImg");
    			Bitmap image = account.Base64Str2Bitmap(bitmap_str);
    			Session.saveBitmap(image, GlobalContext.getInstance().getRootDir()+"66.jpg");
    			
    			res = account.getInstanse().GetProfileImage(76,"",sm.getCurrentSession().getSessionid());
    			bitmap_str = (String) res.data.get("personImg");
    			image = account.Base64Str2Bitmap(bitmap_str);
    			Session.saveBitmap(image, GlobalContext.getInstance().getRootDir()+"76.jpg");*/
            	return null;
            }
            is_logining = false;
            return response.errmsg;
        }
        
        @Override
        protected void onCancelled() {
            super.onCancelled();
            mLoadingDialog.hide();
        }
        
        @Override  
        protected void onPostExecute(String result) 
        {  
        	super.onPostExecute(result);
        	if(null == result)
        	{
        		LoginActivity.this.launchToast(R.string.login_ok);
        		Intent intent = new Intent();
    	        intent.putExtra("categoryname","Liulong");    
    	        intent.setClass(LoginActivity.this, SheetBrowseActivity.class);
    	        LoginActivity.this.startActivity(intent);
    	        //LoginActivity.this.finish();
        	}else
        	{
        		LoginActivity.this.launchToast(result);
        	}
        	mLoadingDialog.hide();	
        }
    }   
}
